package com.controller;

import com.alibaba.fastjson.JSON;
import com.proj.InfoInterface;
import com.proj.TagInterface;
import com.proj.ViewInterface;

import java.util.Vector;

import static com.controller.Utility.errBadRequest;
import static com.controller.Utility.parsePayloadToClassThen;

public class MainController {
    TagInterface tagInterface;
    InfoInterface infoInterface;
    ViewInterface viewInterface;

    public String handle(String payload) {
        String op = (String) JSON.parseObject(payload).get("type");
        String response;

        switch (op) {
            case "req_fuzzySearch": {
                response = parsePayloadToClassThen(payload, jFuzzySearch.class, t -> {
                    // TODO: 也许可以写得更加函数式编程化
                    Vector<Object> results = new Vector<>();
                    for (String st : t.searchType) {
                        int maxEntryThisRound = t.maxEntry - results.size();
                        if (maxEntryThisRound == 0) {
                            break;
                        }

                        switch (st) {
                            case "tag": {
                                results.addAll(tagInterface.fuzzySearch(t.searchString, maxEntryThisRound));
                                break;
                            }
                            case "info": {
                                results.addAll(infoInterface.fuzzySearch(t.searchString, maxEntryThisRound));
                                break;
                            }
                            case "view": {
                                results.addAll(viewInterface.fuzzySearch(t.searchString, maxEntryThisRound));
                                break;
                            }
                            default: {
                                return errBadRequest("unknown search type: " + st);
                            }
                        }
                    }
                    jResultCrate<Object[]> r = new jResultCrate<>("resp_fuzzySearch", results.toArray());
                    return JSON.toJSONString(r);
                });
                break;
            }
            default: {
                response = errBadRequest();
                break;
            }
        }

        return response;
    }

}
